<template>
    <div class="PersonSettingPassWord">
        <!-- 头部 -->
		<Header :navActive="-1" ref="Header"/>
		<!-- 内容区域 -->
		<div class="main cl">
            <!-- banner -->
            <div class="banner"></div>
            <!-- block -->
            <div class="block w1200">
                <div class="left fl">
                    <div class="title">账号设置</div>
                    <ul>
                        <router-link class="active" tag="li" :to="{name:'PersonSettingPassWord'}">修改密码</router-link>
                        <router-link tag="li" :to="{name:'PersonSettingPhone'}">修改手机号</router-link>
                        <router-link tag="li" :to="{name:'PersonSettingWechat'}">绑定微信号</router-link>
                    </ul>
                </div>
                <div class="right fr">
                    <div class="title">当前绑定手机号：<span>{{this.phone}}</span></div>
                    <el-form class="form" :model="form" :rules="rules" ref="form" label-width="120px">
                        <el-form-item label="验证码" prop="captcha">
                            <el-input ref="code" maxlength="6" v-model.trim="form.captcha" placeholder="请输入验证码"></el-input>
                            <el-button type="text" :disabled="disabledFlag" @click="getCode">{{codeName}}</el-button>
                        </el-form-item>

                        <el-form-item label="新密码" prop="password">
                            <el-input v-model="form.password" type="password" placeholder="请输入新密码"></el-input>
                        </el-form-item>

                        <el-form-item label="确认新密码" prop="confirmpassword">
                            <el-input v-model="form.confirmpassword" type="password" placeholder="请确认新密码"></el-input>
                        </el-form-item>


                        <el-form-item>
                            <el-button type="primary" class="btn" @click="submit">确定</el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </div>
        </div>
        <!-- 底部 -->
		<Footer />
    </div>
</template>

<script>
    import {getSmsCode,updatePassword,getSmsCodeToken,signOut} from '@/api/api'
    import '@/util/jsencrypt.min.js';
    import Header from '@/components/Header.vue'
    import Footer from '@/components/Footer.vue'
    export default {
        //组件注入
        components: {Header,Footer,},
        //存放数据
        data() {
            var validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                    } else {
                    if (this.form.confirmpassword !== '') {
                        this.$refs.form.validateField('confirmpassword');
                    }
                    callback();
                    }
                };
                var validatePass2 = (rule, value, callback) => {
                    if (value === '') {
                    callback(new Error('请再次输入密码'));
                    } else if (value !== this.form.password) {
                    callback(new Error('两次输入密码不一致!'));
                    } else {
                    callback();
                    }
                };
            return {
                phone:'',
                phone1:'',
                codeName:'获取验证码',
				disabledFlag: false,//获取验证码能否点击
				time: 60,
                form:{
                    mobile: '',
                    captcha: '', // 验证码
                    password: '',
                    confirmpassword: ''
                },
                rules: {
                     mobile: [
                    { required: true, message: '请输入手机号码', trigger: 'blur' },
                    { validator: this.$telText, trigger: 'blur' }
                    ],
                    password:[ { required: true, message: '请输入密码', trigger: 'blur' },
                    { pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/, message: '密码至少包含 数字和英文，长度6-20位' },
                    { validator: validatePass, trigger: 'blur' }],
                    confirmpassword:[{ required: true, message: '请再次输入密码', trigger: 'blur' },
                    { pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/, message: '密码至少包含 数字和英文，长度6-20位' },
                    { validator: validatePass2, trigger: 'blur' }],
                    captcha: [
                    { required: true, message: '请输入验证码', trigger: 'blur' },
                    ],
                }
            }
        },
        //接受父组件传递的值
        props:[],
        //监控data中的数据变化
        watch: {},
        //方法集合
        methods: {
            //获取验证码
			getCode(){
				//获取验证码token
                    getSmsCodeToken({
                        'phone':this.form.mobile
                    }).then(res =>{
                        if(res.code==200){
                            var token = res.result.token
                            var sign = this.$md5(token+this.form.mobile+'EmxJk0VFBgtPfCU5XtZxiVk6rkIGBLwY')
                            //获取验证码接口
                            getSmsCode({
                                'token': token,
                                'mobile':this.form.mobile,
                                'sign':sign
                            }).then(res =>{
                                if(res.code==200){
                                    this.$message.success('验证码发送成功');
                                    let that = this
                                    that.disabledFlag = true
                                    let interval = window.setInterval(function() {
                                        that.codeName = '已发送' + that.time + 's';
                                        --that.time;
                                        if(that.time < 0) {
                                            that.codeName = "重新发送";
                                            that.time = 60;
                                            that.disabledFlag = false;
                                            window.clearInterval(interval);
                                        }
                                    }, 1000);
                                }else{
                                    this.$message.error(res.message);
                                }
                            });
                        }else{
                            this.$message.error(res.message);
                        }
                    });
            },
            //修改手机号
            submit(){
                this.$refs.form.validate((valid) => {
					if(valid) {

                        let form = JSON.parse(JSON.stringify(this.form))
                        var encrypt = new JSEncrypt();
                        encrypt.setPublicKey('MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDRYwEHVtYKjqQ5VZEzVkPJqSWwokUy7GYZdjB+aUZDNioAWPXZ3A9HlOjp5FLbHEmLtIVt7qFX0U/E8xl9Ar1rePRUOijtxRBjpWTdW9f9DCw6CY7dPcXvxCKbshf1lSYEysu3Kphb+44/meqrGKuYnqJTYQVcjNXSmtMXFto08QIDAQAB');
                        form.password = encrypt.encrypt(form.password);
                        form.confirmpassword = encrypt.encrypt(form.confirmpassword);
                        form.type = "person";
                        updatePassword(form).then(res => {
                             if(res.code==200){
                                this.$message.success('修改成功');
                                //退出登录
                                signOut().then(res =>{
                                    if(res.code==200){
                                        localStorage.setItem('loginStatus',0)
                                        this.$router.push({name:'Login'}) 
                                    }
                                });
                            }else{
                                this.$message.error(res.message);
                            }
                        })
                    }else{
						return false;
                    }
                });
            }
        },
        //生命周期 - 创建完成（可以访问当前this实例）
        created() {},
        //生命周期 - 挂载完成（可以访问DOM元素）
        mounted() {
            //判断登录状态
            this.userLoginFlag()
            let phone = JSON.parse(localStorage.getItem('userInfo')).phone
            let reg = /(\d{3})\d{4}(\d{4})/;
            this.phone = phone.replace(reg,'$1****$2');
            this.phone1 = phone
            this.form.mobile = phone;
        }
    };
</script>
<style lang="scss">
    @mixin text-ellipsis{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
    @mixin text-ellipsisclamp($clamp){display: -webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: $clamp;overflow: hidden;}
    @mixin transition{transition: all .3s;}
    .PersonSettingPassWord{background: #f6f6f6;
        .main{min-height: 500px;
            .banner{width: 100%;height: 120px;background: url('../../assets/person-bg.jpg') center no-repeat;background-size: cover;}
            .block{height: auto;overflow: hidden;margin-top: 30px;padding-bottom: 60px;
                .left{width: 270px;height: auto;overflow: hidden;background: #fff;padding-bottom: 25px;
                    .title{font-size: 18px;color: #333;font-weight: bold;padding: 25px 0;text-align: center;}
                    ul{height: auto;overflow: hidden;
                        li{line-height: 50px;font-size: 16px;color: #999;text-align: center;cursor: pointer;border-top: 1px solid #f6f6f6;position: relative;@include transition();
                            &.active{color: #E54437;
                                &:after{content: "";width: 4px;height: 50px;background: #E54437;position: absolute;left: 0;top: 0;}
                            }
                            &:hover{color: #E54437;}
                        }
                    }
                }
                .right{width: 900px;height: auto;overflow: hidden;background: #fff;padding: 50px 70px 30px;
                    .title{font-size: 14px;color: #333;margin-bottom: 30px;
                        span{color: #999;}
                    }
                    .form{width: 500px;
                        .el-button--text{right: 0;left: auto;position: absolute;padding: 10px 20px;}
                        .btn{width: 170px;}
                        .btnCode{padding: 0;}
                    }
                }
            }
        }
    }
</style>